#---------------------------------#
# Create conflict data            #
#---------------------------------#
rm(list = ls())

## Imputed data
polity.diffusion <- readRDS("data/polity_diffusion_replication.rds")
dyad_data   <- readRDS("intl_order/unweighted_data_replication.rds")
intl_groups <- readRDS("intl_order/international_order_replication.rds")

## Create war data frame with unweighted dyads
war_data <- distinct(
  dyad_data, 
  ccode1, ccode2, year, .keep_all = T 
) %>% dplyr::select(
  c(
    ccode1, ccode2, year, contig, joint_region, 
    cowc1, cowc2, joint_major_power, 
    fatal_mid, mid
  )
) %>% mutate(
  mid_id = paste0(ccode1, "-", ccode2)
)


## Merge in imputed values  
state_data <- dplyr::select(
  polity.diffusion,
    c(
      ccode, year, polity, cinc
    )
)  

## Merge in cooperative regimes
coop_regime <- dplyr::select(
  intl_groups, 
  c(
    ccode, year, interlayer
  )
)

## Create dyad data.frame
war_data <- left_join(
  war_data,
  state_data,
  by = c(
    "ccode1" = "ccode",
    "year"
  )
) %>% left_join(
  state_data,
  by = c(
    "ccode2" = "ccode",
    "year"
  )
) %>% left_join(
  coop_regime, 
  by = c(
    "ccode1" = "ccode",
    "year"
  )
) %>% left_join(
  coop_regime, 
  by = c(
    "ccode2" = "ccode",
    "year"
  )
) %>% dplyr::rename(
  cinca = cinc.x,
  cincb = cinc.y,
  politya = polity.x,
  polityb = polity.y,
  coop_regimea = interlayer.x,
  coop_regimeb = interlayer.y
) %>% mutate(
   cinc_ratio = if_else(cinca > cincb, (cinca - cincb)/(cinca + cincb), (cincb - cinca)/(cinca + cincb)),
   democ_joint = if_else(politya >= 6 & polityb >= 6, 1, 0),
   autoc_joint = if_else(politya <= -6 & polityb <= -6, 1, 0),
   out_group = if_else(coop_regimea != coop_regimeb, 1, 0)
) %>% distinct(
  ccode1, ccode2, year, .keep_all = T
)

## Create state count
state.count <- mutate(
  intl_groups, 
  n = 1
  ) %>% plyr::ddply(
  ~year, 
  summarize,
  state_count = sum(n)
) %>% mutate(
    state_count = state_count - mean(state_count),
    state_count = scale(state_count)
  )

## Create joint major power
war.data <- left_join(
  war_data, 
  state.count, 
  by = "year"
) %>% dplyr::rename(
  major_power_joint = joint_major_power,
  namea = cowc1, 
  nameb = cowc2, 
  dyad = mid_id
)

## Turn it into a data.frame and export
war.data <- data.frame(war.data)
war.data$state_count <- as.numeric(war.data$state_count)
saveRDS(war.data, file = "data/war_data_replication.rds")

## Create tergm data
war.data <- readRDS("data/war_data_replication.rds")

all_data           <- list()
mids               <- list()
fmids              <- list()
cinc_ratio         <- list()
major_power        <- list()
contig             <- list()
joint_democ        <- list()
joint_autoc        <- list()
out_group          <- list()

years <- sort(unique(polity.diffusion$year))
for (i in years)
{
  polity_subset_data <- subset(polity.diffusion, year == i)
  mid_matrix  <- matrix(0, nrow = length(unique(polity_subset_data$names)), ncol = length(unique(polity_subset_data$names)))
  rownames(mid_matrix)  <- colnames(mid_matrix) <- sort(unique(polity_subset_data$names))
  
  ## war data
  subset_war_data <- filter(
    war.data, 
    year == i
  ) %>% dplyr::select(
    c(
      namea, nameb, major_power_joint, mid, fatal_mid, cinc_ratio, democ_joint, autoc_joint, out_group, contig
    )
  ) %>% data.frame(.)
  adj_mat <- igraph::graph.data.frame(subset_war_data[,colnames(subset_war_data) %in% c("out_group", "namea", "nameb", "mid", "fatal_mid",  "cinc_ratio", "major_power_joint", "contig", "democ_joint", "autoc_joint")], directed = F)
  
  ## get mid
  mid_adj_mat <- igraph::get.adjacency(adj_mat, sparse = FALSE, attr = 'mid')
  
  ## get fatal mid
  fmid_adj_mat <- igraph::get.adjacency(adj_mat, sparse = FALSE, attr = 'fatal_mid')
  
  ## get onset 
  #onset_adj_mat <- igraph::get.adjacency(adj_mat, sparse = FALSE, attr = 'onset')
  
  ## get cinc ratio
  cinc_ratio_adj_mat <- igraph::get.adjacency(adj_mat, sparse = FALSE, attr = 'cinc_ratio')
  
  ## get contiguity
  contig_adj_mat <- igraph::get.adjacency(adj_mat, sparse = FALSE, attr = 'contig')
  
  ## get major powers
  major_power_adj_mat <- igraph::get.adjacency(adj_mat, sparse = FALSE, attr = 'major_power_joint')
  
  ## get joint democ
  joint_democ_adj_mat <- igraph::get.adjacency(adj_mat, sparse = FALSE, attr = 'democ_joint')
  
  ## get major powers
  joint_autoc_adj_mat <- igraph::get.adjacency(adj_mat, sparse = FALSE, attr = 'autoc_joint')
  
  ## get joint group
  out_group_adj_mat <- igraph::get.adjacency(adj_mat, sparse = FALSE, attr = 'out_group')
  
  ## get unaffiliated joint
  
  
  mid_net   <- network::network(mid_adj_mat, directed = F)
  fmid_net  <- network::network(fmid_adj_mat, directed = F)
  
  set.vertex.attribute(mid_net, "state_count", as.vector(subset(state.count, year == i)$state_count/2))
  set.vertex.attribute(fmid_net, "state_count", as.vector(subset(state.count, year == i)$state_count/2))
  
  all_data[length(all_data) + 1]                       <- intergraph::asNetwork(adj_mat)
  mids[[length(mids) + 1]]                             <- mid_net
  fmids[[length(fmids) + 1]]                           <- fmid_net
  cinc_ratio[[length(cinc_ratio) + 1]]                 <- cinc_ratio_adj_mat
  contig[[length(contig) + 1]]                         <- contig_adj_mat
  major_power[[length(major_power) + 1]]               <- major_power_adj_mat
  joint_democ[[length(joint_democ) + 1]]               <- joint_democ_adj_mat
  joint_autoc[[length(joint_autoc) + 1]]               <- joint_autoc_adj_mat
  out_group[[length(out_group) + 1]]                   <- out_group_adj_mat
  
  cat(paste0("\rFinished ", i, "."))
}

for (i in 1:length(contig))
{
  states <- sort(colnames(contig[[i]]))
  contig[[i]]      <- contig[[i]][states, states]
  major_power[[i]] <- major_power[[i]][states, states]
  cinc_ratio[[i]]  <- cinc_ratio[[i]][states, states]
  joint_democ[[i]] <- joint_democ[[i]][states, states]
  joint_autoc[[i]] <- joint_autoc[[i]][states, states]
  cinc_ratio[[i]]  <- cinc_ratio[[i]][states, states]
  out_group[[i]]   <- out_group[[i]][states, states]
}


save(mids, file = "data/mids.RData")
save(fmids, file = "data/fmids.RData")
save(cinc_ratio, file = "data/cinc_ratio.RData")
save(contig, file = "data/contig.RData")
save(major_power, file = "data/major_power.RData")
save(joint_democ, file = "data/joint_democ.RData")
save(joint_autoc, file = "data/joint_autoc.RData")
save(out_group, file = "data/out_group.RData")
